// app.js
App({
  globalData: {
    userInfo: null,
    token: '',
    baseUrl: 'https://api.towerfund.com'
  },
  
  onLaunch() {
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    this.globalData.systemInfo = systemInfo;
    
    // 检查登录状态
    this.checkLoginStatus();
    
    // 检查用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      // 确保department字段存在
      if (!userInfo.department) {
        userInfo.department = '财务部';
        wx.setStorageSync('userInfo', userInfo);
      }
      this.globalData.userInfo = userInfo;
    }
  },
  
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (token) {
      this.globalData.token = token;
      // 可以添加token验证逻辑
    }
  },
  
  // 登录方法
  login(callback) {
    wx.login({
      success: res => {
        if (res.code) {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          wx.request({
            url: `${this.globalData.baseUrl}/system/auth/wxLogin`,
            method: 'POST',
            data: {
              code: res.code
            },
            success: loginRes => {
              if (loginRes.data.code === 200) {
                const { token, userInfo } = loginRes.data.data;
                this.globalData.token = token;
                this.globalData.userInfo = userInfo;
                wx.setStorageSync('token', token);
                wx.setStorageSync('userInfo', userInfo);
                
                if (callback) callback(true);
              } else {
                if (callback) callback(false);
              }
            },
            fail: () => {
              if (callback) callback(false);
            }
          });
        } else {
          if (callback) callback(false);
        }
      },
      fail: () => {
        if (callback) callback(false);
      }
    });
  },
  
  // 获取用户信息
  getUserProfile(callback) {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        if (callback) callback(res.userInfo);
      },
      fail: () => {
        if (callback) callback(null);
      }
    });
  }
}); 